import api from '../../api/index';
import { sdk } from '../../config/sdk';
Page({
  data: {
    isLoading: false,
    wxisLoading: false
  },

  onLoad() {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId
        sdk.request({ url: api.getOpenid, data: { code: res.code } })
          .then(res => {
            this.setData({
              openid: res.data.openid
            });
          })
      }
    });
  },

  async getPhoneNumber(e) {
    if (e.detail.errMsg != 'getPhoneNumber:ok') return this.$error('授权失败');
    this.setData({ 
      wxisLoading: true, 
      isLoading: true
    });
    const { code, message, data } = await sdk.request({ url: api.login, data: { code: e.detail.code, openid: this.data.openid } });
    this.setData({ 
      wxisLoading: false, 
      isLoading: false 
    });
    if (code != 1000) return this.$error(message);
    const nowTime = Math.round(new Date() / 1000);
    const token = {
      token: data.token,
      expire: nowTime + data.expire,
      refreshToken: data.refreshToken,
      refreshExpire: nowTime + data.refreshExpire,
    }
    wx.setStorageSync('login', true);
    wx.setStorageSync('token', token);
    this._backPage();
  }
})